﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DIPLib.Filters
{
    public class Laplacian
    {
        public static void doIt(byte[] rgbData, int width, int height, int[] magMatrix)
        {
            MyBitmap bitmap = new MyBitmap(rgbData, width, height);
            byte[] rgbDataSrc = (byte[])rgbData.Clone();
            MyBitmap bitmapSrc = new MyBitmap(rgbDataSrc, width, height);

            byte[] matrix = new byte[9];

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    // Fill the matrix
                    int c = 0;

                    for (int a = 0; a < 3; a++)
                    {
                        int ir = row + a - 1;

                        for (int b = 0; b < 3; b++)
                        {
                            int jc = col + b - 1;

                            int useCol = jc;
                            int useRow = ir;

                            if (jc >= width)
                            {
                                useCol = width - 1;
                            }
                            if (jc < 0)
                            {
                                useCol = 0;
                            }

                            if (ir >= height)
                            {
                                useRow = height - 1;
                            }
                            if (ir < 0)
                            {
                                useRow = 0;
                            }

                            matrix[c++] = bitmapSrc.getPixel(useCol, useRow);
                        }
                    }

                    int sum = 0;
                    for (int index = 0; index < magMatrix.Length; index++)
                    {
                        sum += magMatrix[index] * matrix[index];
                    }
                    byte value = (byte)(sum < 0 ? 0 : (sum > 255 ? 255 : sum));
                    bitmap.setPixel(col, row, value);
                }
            }

            int size = width * height;

            for (int i = 0; i < size; i++)
            {
                int sub = rgbDataSrc[4 * i] - rgbData[4 * i];
                byte value = (byte)(sub < 0 ? 0 : (sub > 255 ? 255 : sub));
                rgbData[4 * i] = rgbData[4 * i + 1] = rgbData[4 * i + 2] = value;
            }
        }
    }
}
